package yb.ecp.fast.user.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.user.dao.mapper.RoleAuthMapper;
import yb.ecp.fast.user.dao.mapper.RoleMapper;
import yb.ecp.fast.user.dao.mapper.RoleMenuMapper;
import yb.ecp.fast.user.infra.ErrorCode;

import java.util.List;

/**
 * Created by LiChangjiang on 2017/12/27 0027.
 */
@Service
public class RoleService
{

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleAuthMapper roleAuthMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;


    @Value("${role.admin.roleId}")
    private String adminRoleId;

    /**
     * 校验该用户是否有当前工作空间的管理员权限<br/>
     * 如果是管理员，返回TRUE
     *
     * @param roleIds List
     * @return boolean
     */
    public boolean ifAdminRole(List<String> roleIds)
    {
        //判断该用户是否是管理员角色
        return roleIds.contains(adminRoleId.trim());
    }

    /**
     * 判断用户是否管理员<br />
     * 如果是管理员，返回TRUE
     *
     * @param userId String
     * @return boolean
     */
    public boolean ifAdminUser(String userId)
{
    List<String> roleIds =  this.queryRoleIdsByUserId(userId);

    return this.ifAdminRole(roleIds);
}

    /**
     * 查询工作空间下的角色ID集合
     * @param workspaceId String
     * @return List
     */
    public List<String> queryIdsByWorkspaceId(String workspaceId)
    {
        return  roleMapper.selectByWorkspaceId(workspaceId);
    }

    /**
     * 查询用户所有角色ID
     * @param userId
     * @return
     */
    public List<String> queryRoleIdsByUserId(String userId)
    {
        return  roleMapper.selectRoleIdsByUserId(userId);
    }

    /**
     * 解除角色与权限、menu之间的关联
     * @param roleId String
     */
    public void releaseAuthMenu(String roleId)
    {
        roleAuthMapper.deleteAuth(roleId);
        roleMenuMapper.deleteMenu(roleId);
    }

    /**
     * 解除工作空间下角色与权限、menu关联关系
     * @param workspaceId String
     * @return  ErrorCode
     */
    public ErrorCode releaseByWorkspace(String workspaceId)
    {
        List<String> roleIds = queryIdsByWorkspaceId(workspaceId);

        if (ListUtil.isNullOrEmpty(roleIds))
        {
            return ErrorCode.Success;
        }

        for (String roleId : roleIds)
        {
            releaseAuthMenu(roleId);
        }

        return ErrorCode.Success;
    }
}
